package com.iflyings.android.dataconfig

import android.content.Context
import android.database.ContentObserver
import android.net.Uri
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.channels.onFailure
import kotlinx.coroutines.channels.trySendBlocking
import kotlinx.coroutines.flow.callbackFlow
import org.json.JSONObject

fun getNotifyValueChangeUri(name: String): Uri {
    return if (name.isEmpty())
        ConfigContentProvider.getNotifyUri(ConfigContentProvider.TABLE_NAME)
    else
        Uri.withAppendedPath(ConfigContentProvider.getNotifyUri(ConfigContentProvider.TABLE_NAME), name)
}

fun dbCreate(filePath: String) = IniSection.init(filePath)

inline fun <reified T: Any> dbLoader(defaultValue: T) = DBLLoaderImpl(defaultValue, T::class.java)

inline fun <reified T: Any> dbRLoader(defaultValue: T) = DBRLoaderImpl(defaultValue, T::class.java)

fun dbItemFlow(context: Context, name: String) = callbackFlow {
    val contentResolver = context.contentResolver
    val observer = object: ContentObserver(null) {
        override fun onChange(selfChange: Boolean, uri: Uri?) {
            super.onChange(selfChange, uri)
            if (uri != null) {
                trySendBlocking(name).onFailure { close() }
            }
        }
    }

    contentResolver.registerContentObserver(getNotifyValueChangeUri(name), true, observer)
    awaitClose { contentResolver.unregisterContentObserver(observer) }
}

fun loadJSONObject(filePath: String): JSONObject? = FileUtils.readJSON(filePath)

fun saveJSONObject(filePath: String, jsonObject: JSONObject) = FileUtils.writeJSON(filePath, jsonObject)

